﻿var fs_maxWindow = false;
firstColumns = [
              { index: 0, headerText: "YTD M-1", edit: true, style: 'gray', readonly: true, width: 80, rowText: "YTDM_1" },
              { index: 2, headerText: "YTD", currentrow: true, edit: true, style: 'blue', readonly: true, width: 80, rowText: "YTD" },
              { index: 1, headerText: "Current Month", edit: true, style: '', width: 80, rowText: "CM" }
            ];



function createSelfLineFieldCalc(self, process) {
    var expression = "";
    self[process.Field + "style"] = "blue";
    process.Exp.fields.forEach(function (field) {
        var v = unWarpValue(self[field]);

        expression += String.format("({0}){1}", v, process.Exp.equ);
    });

    return commonAdditionCalculate(expression, self.addition, self.digits);

}

function commonAdditionCalculate(expression, addition, digits) {

    expression = expression.substring(0, expression.length - 1);

    total = fs.util.eval(expression);

    if (addition) {
        total = fs.util.eval(String.format(addition, total));
    }

    if (!isNaN(total))
        return total.toFix(digits)

    return 0.00
}
var newFormAction = fs.form.mode == 'New';
var editFormAction = fs.form.mode == 'Edit';
var displsyFormAction = fs.form.mode == 'Display';

function createField(self, instance) {
    var CM = parseFloat(unWarpValue(instance["CM"])) ? parseFloat(unWarpValue(instance["CM"])) : 0.00;
    var YTDM_1 = parseFloat(unWarpValue(instance["YTDM_1"])) ? parseFloat(unWarpValue(instance["YTDM_1"])) : 0.00;
    var YTD = parseFloat(unWarpValue(instance["YTD"])) ? parseFloat(unWarpValue(instance["YTD"])) : 0.00;
    var LM = parseFloat(unWarpValue(instance["LM"])) ? parseFloat(unWarpValue(instance["LM"])) : 0.00;


    instance.digits = typeof instance.digits == 'undefined' ? instance.parent.digits : instance.digits;

    self["YTDM_1"] = YTDM_1;

    if (newFormAction || editFormAction) {

        self["YTDM_1"] = parseFloat(fs.util.strFilter(getLastMonthFieldData(self.accountcode, "CM", instance.digits))) + parseFloat(fs.util.strFilter(getLastMonthFieldData(self.accountcode, "YTDM_1", instance.digits)));
        self["LM"] = parseFloat(fs.util.strFilter(getLastMonthFieldData(self.accountcode, "CM", instance.digits)));
    } else {
        self["LM"] = LM.toFix(instance.digits);
        self["YTD"] = YTD.toFix(instance.digits);
    }

    if (fs.form.month == 1) {
        self["YTDM_1"] = 0;
    }

    var defaultCMCalc = function () {
        CM = newFormAction ? 0 : CM;
        self["CM"] = ko.observable(CM.toFix(instance.digits));

    }

    if (self.subrow && !instance.Process) {
        defaultCMCalc();
    }

    if (self.datarow || instance.controlrow) {
        defaultCMCalc();
        if (self.Process) {
            if (!displsyFormAction) {
                expressionConnector(self, { rowText: "CM" }, instance);
                expressionConnector(self, { rowText: "YTD" }, instance);
            }
        }
    }

    //    if (instance.parent.Process) {
    //        defaultCMCalc();
    //        commonProcess(self, instance);
    //    }
}

function commonProcess(self, instance) {

    $(instance.parent.Process).each(function () {
        var process = this;

        self[process.Field + "style"] = "blue";

        self[process.Field] = ko.computed(function () {
            var expression = process.Exp.mutilFieldType ? process.Exp.equ : "", total = 0, index = 0;

            process.Exp.fields.forEach(function (field) {
                var endWithx = field.endWith('x');
                var identity = '';
                var fieldtype = process.Exp.fieldtype ? process.Exp.fieldtype : process.Field;
                var accountcode = instance.accountcode;

                if (process.Exp.mutilFieldType) {
                    var fieldGroup = field.split("|");
                    field = fieldGroup[1];
                    fieldtype = fieldGroup[0];
                }

                if (endWithx) {
                    var end = accountcode.substr(9, accountcode.length);
                    identity = field.substr(0, 9) + end;
                }
                else
                    identity = field;

                var v = getSubrowValueByIdentity(identity, fieldtype);
                if (process.Exp.mutilFieldType)
                    expression = expression.replace("{" + index + "}", v);
                else
                    expression += v + process.Exp.equ;

                index++;
            });

            expression = expression.substring(0, expression.length - 1);

            total = fs.util.eval(expression);

            if (instance.parent.addition) {
                total = fs.util.eval(String.format(instance.parent.addition, total));
            }

            if (!isNaN(total))
                return total.toFix(instance.digits)

            return 0.00;
        });
    });

}

var afterSearchBinding = function (items) {

    items.forEach(function (self) {

        //  if (typeof self["YTD"] == 'undefined') {
        if (!self.mutilFieldType && !self.withYTD && !displsyFormAction) {
            self["YTD"] = ko.computed(function () {
                return (parseFloat(unWarpValue(self['YTDM_1'])) + parseFloat(unWarpValue(self['CM']))).toFix(self.digits);
            })

            self.rowAfterBinding && self.rowAfterBinding(self);
        }
    });
}

function Item(instance) {
    var self = this;
    instance.description = instance.description.replace("&amp;", "&");

    self.headrow = self.emptyrow = self.datarow = self.controlrow = self.withsubrow = self.bold, self.insertcontrol = false;

    self.insertcontrol = instance.insertcontrol ? instance.insertcontrol : false;
    self.bold = instance.bold ? instance.bold : false;
    self.hide = instance.hide ? instance.hide : false;
    self.unit = instance.unit ? fs_unitMerger(instance.unit) : fs.form.entitycurrency;
    self.digits = typeof instance.digits != "undefined" ? instance.digits : fs.sys.defaultDigits;

    self.rowAfterBinding = instance.rowAfterBinding;
    self.CMstyle = instance.CMstyle;
    self.withYTD = instance.withYTD;
    self.mutilFieldType = instance.mutilFieldType;
    self.controlrow = instance.controlrow ? instance.controlrow : false;
    self.datarow = instance.datarow;
    self.Process = instance.Process;
    self.allowCopyDataFromLastMonth = instance.allowCopyDataFromLastMonth;
    self.dataFromLastMonth = instance.dataFromLastMonth;

    self.accountcode = instance.accountcode;
    self.description = instance.description;
    self.defaultValue = instance.defaultValue;
    self.addition = instance.addition;

    self.style = ko.observable(instance.style);
    self.styleInit = function (col, row) {
        if (col.hide) return "fs_disable";
        if (col.style) return col.style;
        var style = row[col.rowText + 'style'];
        col.calcfield = style ? true : false
        if (style) return style;
        if (unWarpValue(row.style)) return row.style;
        return style;
    }
    self.manual = function (col, row) {
        if (typeof row[col.rowText] == 'undefined' || fs.form.mode == 'Display' || col['readonly'])
            return false;

        var style = self.styleInit(col, row);
        return style != "blue" && style != "green";
    }

    if (instance.emptyrow) {
        self.emptyrow = instance.emptyrow;
        self.description = instance.description;
        self.accountcode = "";
        return self;
    }

    instance.parent = self;

    if (instance.subrow) {
        self.withsubrow = true;
        self.subrow = ko.observableArray([]);
        instance.subrow.forEach(function (obj) {
            obj.parent = self;
            self.subrow.push(new subentity(obj));
        });

        self.addItem = function () {
            var newAccountID = self.subrow().length;

            self.subrow.push(new subentity({ parent: instance.parent, accountcode: instance.accountcode + "-" + newAccountID, description: instance.description, subskip: instance.subskip }));
        }
        self.removeItem = function (item) {
            self.subrow.remove(item);
        }
        //self.style("blue");
    }

    if (instance.datarow || instance.controlrow) {
        createField(self, instance);
    }

    return self;
}
columnsCategory = null;

fs.util.pageLoadFunction.push(function () {

    window.viewModel = {
        entitys: fs.form.allEntity,
        categories: fs.form.allRGC,
        firstColumns: firstColumns,
        columns: firstColumns,
        columnsCategory: columnsCategory,
        items: ko.observableArray([])
    };

});